package org.example.old.controller;


//import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.old.dto.SysDto;
import org.example.old.service.SysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;

@RequestMapping("/sys")
@RestController
//@RefreshScope
public class TestController {


    @Value("${spring.datasource.maxActive}")
    private String nacosMaxActiveType;
    @Value("${server.port}")
    private  Integer serverPort;

    private static Integer serverPort222;
    @Autowired
    SysService service;


    // 初始化方法
    @PostConstruct
    public void init(){
        this.serverPort222 = serverPort;
    }
//
//    public TestController() {
//        // 调用userService的自定义初始化方法，此时userService为null，报错
//        service.querList();
//    }


    @GetMapping(value = "nacos")
    public String nacosA(@PathVariable("id") String id) {
        return nacosMaxActiveType;
    }

    @GetMapping("/api/ribbon")
    public  String  testRibbon() {
        return  "现在访问的服务端口是:" + serverPort222 ;
    }


    @GetMapping("/sentinel/protected")
    @SentinelResource(value ="goods", blockHandler = "sendMsgBlockHandler")
    public  PageInfo  sentinelProtected(@RequestParam("pageNum") int pageNum,@RequestParam("pageSize") int  pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        // 不带分页的查询
        List<SysDto> list = service.querList();
        // 可以将结果转换为 Page , 然后获取 count 和其他结果值
        PageInfo pageInfo=new PageInfo(list);

        return pageInfo;
    }

    public String sendMsgBlockHandler(  BlockException e) {
        return "该接口被限流了";
    }

    @GetMapping(value = "sentinel/slow/request/ratio")
    public  String  sentinelRR() {
        try {
            double randomNumber;
            randomNumber = Math.random();
            if (randomNumber >= 0 && randomNumber <= 0.80) {
                Thread.sleep(300L);
            } else if (randomNumber >= 0.80 && randomNumber <= 0.80 + 0.10) {
                Thread.sleep(10L);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "慢调用比例熔断策略" ;
    }

    @GetMapping(value = "sentinel/error/ratio")
    public String sentinelRatio() {
        int i = 1/0;
        return  "异常比例熔断策略" ;
    }

    @GetMapping(value = "sentinel/error/count")
    public String sentinelCount() {
        int i = 1/0;
        return  "异常数熔断策略" ;
    }


}
